package org.vehicle.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.vehicle.entity.OrganizationInfo;
import org.vehicle.entity.security.MyUserDetail;
import org.vehicle.service.OrganizationInfoService;
import org.vehicle.util.ExcelUtil;


@Controller
public class OrganizationInfoController {
	private static Logger logger = LogManager.getLogger(OrganizationInfoController.class.getName());

    @Autowired
    private OrganizationInfoService organizationInfoService;

    @RequestMapping("organizationInfo")
    public String mapInfo(HttpServletRequest req, Model model) {
    	MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		model.addAttribute("manager", ud);
        return "organizationInfo";
    }

    /**
     * @param request
     * @return
     * @describe: 获取检查站集合
     * @Author: ruifight2018
     * @Date: 2018年6月8日 上午11:47:58
     */
    @RequestMapping("/getOrganizationListList")
    @ResponseBody
    public Map<String, Object> getOrganizationListList(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
        String currentPage = request.getParameter("curr");
        String pageSize = request.getParameter("pageSize");
        String organizationName = request.getParameter("organizationName");
        try {
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("startPage", (Integer.parseInt(currentPage) - 1) * Integer.parseInt(pageSize));
            paramMap.put("pageSize", Integer.parseInt(pageSize));
            paramMap.put("organizationName", organizationName);
            map = organizationInfoService.getOrganizationInfoListList(paramMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * @return
     * @describe:添加/修改检查站
     * @Author: ruifight2018
     * @Date: 2018年6月11日 上午11:11:56
     */
    @RequestMapping("/saveOrUpdateOrganizationInfo")
    @ResponseBody
    public Map<String, Object> saveOrUpdateOrganizationInfo(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            String id = request.getParameter("organizationInfoId");
            MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            String organizationName = request.getParameter("organizationName");
            String longitude = request.getParameter("longitude");
            String latitude = request.getParameter("latitude");

            OrganizationInfo organizationInfo = new OrganizationInfo();
            organizationInfo.setOrganizationName(organizationName);
            organizationInfo.setLongitude(longitude);
            organizationInfo.setLatitude(latitude);
            organizationInfo.setOrganizationType(2002);
            organizationInfo.setParentOrganizationInfoId(ud.getOrganizationInfoId());
            organizationInfo.setState(1);
            Map<String, Object> paramMap=new HashMap<String, Object>();
        	paramMap.put("organizationInfoId", id);
        	paramMap.put("organizationName", organizationName);
        	OrganizationInfo tempOrganizationInfo=organizationInfoService.getOrganizationInfoByName(paramMap);
        	if(tempOrganizationInfo!=null){
        		map.put("state", 0);
                map.put("msg", "检查站名称已经存在");
                return map;
        	}
            if (null != id && !id.equals("")) {
                long organizationInfoId = Long.parseLong(id);
                organizationInfo.setOrganizationInfoId(organizationInfoId);
                organizationInfoService.updateByPrimaryKeySelective(organizationInfo);
                map.put("state", 1);
                map.put("msg", "修改成功");
            } else {
                organizationInfoService.insertSelective(organizationInfo);
                map.put("state", 1);
                map.put("msg", "添加成功");
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            map.put("state", 0);
            map.put("msg", "操作错误");
        }

        return map;
    }

    /**
     * @param key
     * @return
     * @describe: 回显
     * @Author: ruifight2018
     * @Date: 2018年6月11日 下午6:11:39
     */
    @RequestMapping("viewOrganizationInfo")
    @ResponseBody
    public OrganizationInfo viewOrganizationInfo(Long key) {
        OrganizationInfo organizationInfo = organizationInfoService.selectByPrimaryKey(key);
        return organizationInfo;
    }

    /**
     * @param key
     * @return
     * @describe: 删除
     * @Author: ruifight2018
     * @Date: 2018年6月11日 下午6:43:31
     */
    @RequestMapping("delTripinfo")
    @ResponseBody
    public Map<String, Object> delTripinfo(Long key) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            int i = organizationInfoService.deleteByPrimaryKey(key);
            map.put("num", 1);
            map.put("msg", "删除成功");
        } catch (Exception e) {
            // TODO: handle exception
            map.put("num", 0);
            map.put("msg", "删除失败");
        }
        return map;
    }

    /**
     * @describe: 获取全部检查站(不包括根检查站),添加检查站用
     * @params:
     * @Author: Kanyun
     * @Date: 2018/6/15 0015 11:53
     */
    @RequestMapping("/getAllOrganizationInfoExceptRoot")
    @ResponseBody
    public List<OrganizationInfo> getAllOrganizationInfoExceptRoot(){
        List<OrganizationInfo> organizationInfos =organizationInfoService.getAllOrganizationInfoExceptRoot();
        return organizationInfos;
    }
    
    
    /**
	 * 导入黑名单
	 * @param req
	 * @return
	 */
	@RequestMapping("importOrganization")
	@ResponseBody
	public Map<String, Object> importOrganization(HttpServletRequest req){
        MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		Map<String, Object> map=new HashMap<String, Object>();
		List<Map<String, String>> dataList=new ArrayList<Map<String, String>>();;
		Map<String, Object> dataMap=ExcelUtil.getExcelData(req);
		String errorMsg=(String) dataMap.get("errorMsg");
		map.put("errorMsg", errorMsg);
		if(!StringUtils.isEmpty(errorMsg)){
			 map.put("errorMsg", errorMsg);
			 return map;
		}
		dataList=(List<Map<String, String>>) dataMap.get("dataList");
		for(Map<String, String> cellMap:dataList){
			OrganizationInfo organizationInfo=new OrganizationInfo();
			if(StringUtils.isEmpty(cellMap.get("col0"))&&StringUtils.isEmpty(cellMap.get("col1"))&&StringUtils.isEmpty(cellMap.get("col2"))){
				continue;
			}else{
				String organizationName=cellMap.get("col0");
				String longitude=cellMap.get("col1");
				String latitude=cellMap.get("col2");
				try{
					organizationInfo.setOrganizationName(organizationName);
					organizationInfo.setLatitude(latitude);
					organizationInfo.setLongitude(longitude);
					organizationInfo.setParentOrganizationInfoId(ud.getOrganizationInfoId());
					organizationInfo.setOrganizationType(2002);
					organizationInfo.setState(1);
					try{
						if(StringUtils.isEmpty(organizationName)){
			        		cellMap.put("msg", "检查站名称不能为空");
			        		continue;
			        	}
						if(StringUtils.isEmpty(latitude)){
			        		cellMap.put("msg", "检查站纬度不能为空");
			        		continue;
			        	}
						if(StringUtils.isEmpty(longitude)){
			        		cellMap.put("msg", "检查站经度不能为空");
			        		continue;
			        	}
						Map<String, Object> paramMap=new HashMap<String, Object>();
			        	paramMap.put("organizationName", organizationName);
			        	OrganizationInfo tempOrganizationInfo=organizationInfoService.getOrganizationInfoByName(paramMap);
			        	if(tempOrganizationInfo!=null){
			        		cellMap.put("msg", "检查站名称已经存在");
			        		continue;
			        	}
						organizationInfoService.insertSelective(organizationInfo);
						cellMap.put("msg", "添加成功");
					}catch(Exception e){
						cellMap.put("msg", e.getMessage());
					}
					
				}catch(Exception e){
					logger.error("导入检查站异常", e);
					cellMap.put("msg", "添加失败");
				}
			}
		}
		map.put("dataList", dataList);
		return map;
	}
}
